﻿ 
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls; 
using UnityEngine;
using UnityEngine.Networking;
using XFGameFramework.Localization;
 

public class SteamAchievementModel
{
    public int order;

    public string ID;

    public string Name;

    public string Des;

    public SteamAchievementModel(string ID,int order)
    {
        this.ID = ID;
        this.order = order;
    }

}


public class SteamAchievementData
{
    public string language;

    public Dictionary<string, SteamAchievementModel> models = new Dictionary<string, SteamAchievementModel>();

    public string file_path;


    public bool Empty
    {
        get {

            if (string.IsNullOrEmpty(language)) return true;

            if (models.Count == 0) return true;

            return false;
        }
    }

}


#if UNITY_6000_2_OR_NEWER
public class SteamAchievementTreeItem : TreeViewItem<int>
#else
public class SteamAchievementTreeItem : TreeViewItem
#endif

{
    public string ID;


    public TranslateState request_name_state;

    public TranslateState request_des_state;

    private UnityWebRequest request_name;

    private UnityWebRequest request_des;

    private TranslateAPI api;

    private SteamAchievementData source;
    private SteamAchievementData target;

    public bool name_translate_success;
    public bool des_translate_success;

    public string error;

    public int retry_count;

    public SteamAchievementTreeItem(string ID ) : base(ID.GetHashCode())
    {
        this.ID = ID;
        request_name_state = TranslateState.Wait;
        request_des_state = TranslateState.Wait;
        name_translate_success = false;
        des_translate_success = false;
    }

    public void Translate(TranslateAPI api, SteamAchievementData source, SteamAchievementData target, SystemLanguage to, int need_intervene, string vocabId)
    {
        if (name_translate_success && des_translate_success)
            return;

        this.api = api;

        

        this.source = source;
        this.target = target;

        //error = string.Empty;

        SystemLanguage from = SteamTranslateController.GetSystemLanguage(source.language);

        if (from == SystemLanguage.Unknown)
        {
            error = string.Format("解析源语言错误:{0}", source.language);
            request_name_state = TranslateState.Completed;
            request_des_state = TranslateState.Completed;
            return;
        }

        string l = SteamTranslateController.GetSteamLanguage(to);

        if (string.IsNullOrEmpty(l))
        {
            error = string.Format("解析目标语言错误:{0}", l);
            request_name_state = TranslateState.Completed;
            request_des_state = TranslateState.Completed;
            return;
        }

        switch (api)
        {
            case TranslateAPI.Baidu:
                if (!name_translate_success && request_name_state == TranslateState.Wait)
                {
                    request_name_state = TranslateState.InTranslation;
                    request_name = TranslateController.TranslateBaidu(from, to, source.models[ID].Name, need_intervene);
                }
                if (!des_translate_success && request_des_state == TranslateState.Wait)
                {
                    request_des_state = TranslateState.InTranslation;
                    request_des = TranslateController.TranslateBaidu(from, to, source.models[ID].Des, need_intervene);
                }
                break;
            case TranslateAPI.Youdao:
                if (!name_translate_success && request_name_state == TranslateState.Wait)
                {
                    request_name = TranslateController.TranslateYoudao(from, to, source.models[ID].Name, vocabId);
                    request_name_state = TranslateState.InTranslation;
                }
                if (!des_translate_success && request_des_state == TranslateState.Wait)
                { 
                    //Debug.Log("有道翻译"); 
                    request_des = TranslateController.TranslateYoudao(from, to, source.models[ID].Des, vocabId);
                    request_des_state = TranslateState.InTranslation;
                }

                break;
        }
    }

    public void Update()
    {

        if (request_name != null)
        {
            if (request_name.isDone)
            {
                request_name_state = TranslateState.Completed;

                switch (api)
                {
                    case TranslateAPI.Baidu:

                        BaiduTranslateResult baidu_result = JsonConvert.DeserializeObject<BaiduTranslateResult>(request_name.downloadHandler.text);

                        if (baidu_result != null && !baidu_result.isError)
                        {
                            if (!target.models.ContainsKey(ID))
                                target.models.Add(ID, new SteamAchievementModel(ID, source.models[ID].order));

                            target.models[ID].Name = baidu_result.result.Replace('\"', '\'');
                            name_translate_success = true;

                        }

                        if (baidu_result != null && baidu_result.error_code == "54003" && retry_count < 25)
                        {
                            retry_count++;
                            // 说明访问频率受限  可以再试一次
                            request_name_state = TranslateState.Wait;
                        }

                        if(baidu_result != null && baidu_result.isError)
                            error = baidu_result.error;

                        break;
                    case TranslateAPI.Youdao:

                        YoudaoTranslateResult youdao_result = JsonConvert.DeserializeObject<YoudaoTranslateResult>(request_name.downloadHandler.text);

                        if (youdao_result != null && !youdao_result.isError)
                        {
                            if (!target.models.ContainsKey(ID))
                                target.models.Add(ID, new SteamAchievementModel(ID, source.models[ID].order));

                            target.models[ID].Name = youdao_result.result.Replace('\"', '\'');
                            name_translate_success = true; 
                        }


                        if (youdao_result != null)
                        {
                            if (youdao_result.errorCode == "411" || youdao_result.errorCode == "412")
                            {
                                if (retry_count < 60)
                                {
                                    retry_count++;

                                    //Debug.LogFormat("id:{0} count:{1} NAME",ID,retry_count);

                                    // 说明访问频率受限  可以再试一次
                                    request_name_state = TranslateState.Wait;
                                }
                            }
                        }

                        if (youdao_result != null && youdao_result.isError)  
                            error = youdao_result.error;

                        break;
                }


                request_name = null;

                if (des_translate_success && name_translate_success)
                    error = string.Empty;
            }
        }


        if (request_des != null)
        {
            if (request_des.isDone)
            {

                request_des_state = TranslateState.Completed;
                  
                switch (api)
                {
                    case TranslateAPI.Baidu:

                        BaiduTranslateResult baidu_result = JsonConvert.DeserializeObject<BaiduTranslateResult>(request_des.downloadHandler.text);

                        if (baidu_result != null && !baidu_result.isError)
                        {
                            if (!target.models.ContainsKey(ID))
                                target.models.Add(ID, new SteamAchievementModel(ID, source.models[ID].order));

                            target.models[ID].Des = baidu_result.result.Replace('\"', '\'');
                            des_translate_success = true;
                        }

                        if (baidu_result != null && baidu_result.error_code == "54003" && retry_count < 25)
                        {
                            retry_count++;
                            // 说明访问频率受限  可以再试一次
                            request_des_state = TranslateState.Wait;
                        }

                        if (baidu_result != null && baidu_result.isError)
                            error = baidu_result.error;

                        break;
                    case TranslateAPI.Youdao:

                        YoudaoTranslateResult youdao_result = JsonConvert.DeserializeObject<YoudaoTranslateResult>(request_des.downloadHandler.text);
                         
                        if (youdao_result != null && !youdao_result.isError)
                        {
                            if (!target.models.ContainsKey(ID))
                                target.models.Add(ID, new SteamAchievementModel(ID, source.models[ID].order));

                            target.models[ID].Des = youdao_result.result.Replace('\"', '\'');
                            des_translate_success = true; 
                        }

                        if (youdao_result != null)
                        {
                            if (youdao_result.errorCode == "411" || youdao_result.errorCode == "412")
                            {
                                if (retry_count < 60)
                                {
                                    //Debug.LogFormat("id:{0} count:{1} DES", ID, retry_count);
                                    retry_count++;
                                    // 说明访问频率受限  可以再试一次
                                    request_des_state = TranslateState.Wait;
                                }
                            }
                        }

                        if (youdao_result != null && youdao_result.isError)
                            error = youdao_result.error;

                        break;
                }


                request_des = null;

                if (des_translate_success && name_translate_success)
                    error = string.Empty;

            }
        }




    }

}

#if UNITY_6000_2_OR_NEWER
public class SteamAchievementListTree : TreeView<int>
#else
public class SteamAchievementListTree : TreeView
#endif

{
    public SteamAchievementData source;

    public SteamAchievementData target;

    public bool isError;

#if UNITY_6000_2_OR_NEWER
    private List<TreeViewItem<int>> allItems = new List<TreeViewItem<int>>();
#else
    private List<TreeViewItem> allItems = new List<TreeViewItem>();
#endif


    #region 重写方法

    internal static MultiColumnHeaderState CreateDefaultMultiColumnHeaderState()
    {
        return new MultiColumnHeaderState(GetColumns());
    }
    private static MultiColumnHeaderState.Column[] GetColumns()
    {
        var retVal = new MultiColumnHeaderState.Column[] {
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
                new MultiColumnHeaderState.Column(),
            };
        retVal[0].headerContent = new GUIContent("ID", "语言配置唯一标识");
        retVal[0].minWidth = 50;
        retVal[0].width = 200;
        retVal[0].maxWidth = 500;
        retVal[0].headerTextAlignment = TextAlignment.Left;
        retVal[0].canSort = false;
        retVal[0].autoResize = true;

        retVal[1].headerContent = new GUIContent("源语言", "源语言");
        retVal[1].minWidth = 60;
        retVal[1].width = 100;
        retVal[1].maxWidth = 300;
        retVal[1].headerTextAlignment = TextAlignment.Left;
        retVal[1].canSort = false;
        retVal[1].autoResize = true;

        retVal[2].headerContent = new GUIContent("源名称", "源名称");
        retVal[2].minWidth = 50;
        retVal[2].width = 100;
        retVal[2].maxWidth = 200;
        retVal[2].headerTextAlignment = TextAlignment.Left;
        retVal[2].canSort = false;
        retVal[2].autoResize = true;

        retVal[3].headerContent = new GUIContent("源描述", "源描述");
        retVal[3].minWidth = 100;
        retVal[3].width = 260;
        retVal[3].maxWidth = 800;
        retVal[3].headerTextAlignment = TextAlignment.Left;
        retVal[3].canSort = false;
        retVal[3].autoResize = true;


        retVal[4].headerContent = new GUIContent("翻译名称", "翻译名称");
        retVal[4].minWidth = 60;
        retVal[4].width = 120;
        retVal[4].maxWidth = 300;
        retVal[4].headerTextAlignment = TextAlignment.Left;
        retVal[4].canSort = false;
        retVal[4].autoResize = true;

        retVal[5].headerContent = new GUIContent("翻译描述", "翻译描述");
        retVal[5].minWidth = 60;
        retVal[5].width = 100 * 2;
        retVal[5].maxWidth = 500;
        retVal[5].headerTextAlignment = TextAlignment.Left;
        retVal[5].canSort = false;
        retVal[5].autoResize = true;

        retVal[6].headerContent = new GUIContent("状态", "状态");
        retVal[6].minWidth = 60;
        retVal[6].width = 200;
        retVal[6].maxWidth = 500;
        retVal[6].headerTextAlignment = TextAlignment.Left;
        retVal[6].canSort = false;
        retVal[6].autoResize = true;



        return retVal;
    }

#if UNITY_6000_2_OR_NEWER
    protected override TreeViewItem<int> BuildRoot()
#else
    protected override TreeViewItem BuildRoot()
#endif

    {
        return CreateView();
    }

    protected override void RowGUI(RowGUIArgs args)
    {
        for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
            CellGUI(args.GetCellRect(i), args.item as SteamAchievementTreeItem, args.GetColumn(i), ref args);
    }


#if UNITY_6000_2_OR_NEWER
    protected override IList<TreeViewItem<int>> BuildRows(TreeViewItem<int> root)
#else
    protected override IList<TreeViewItem> BuildRows(TreeViewItem root)
#endif

    {
        return base.BuildRows(root);
    }


    protected override void ContextClicked()
    {
        base.ContextClicked();

    }

    protected override void ContextClickedItem(int id)
    {
        base.ContextClickedItem(id);

        GenericMenu menu = new GenericMenu();
        menu.AddItem(new GUIContent("编辑"), false, () =>
        {
            SteamAchievementTreeItem item = FindItem(id, rootItem) as SteamAchievementTreeItem;
            EditorWindow.GetWindow<EditSteamAchievementWindow>().Init(item.ID, source, target);
        });

        menu.ShowAsContext();
    }

    protected override void DoubleClickedItem(int id)
    {
        base.DoubleClickedItem(id);

        SteamAchievementTreeItem item = FindItem(id, rootItem) as SteamAchievementTreeItem;

        EditorWindow.GetWindow<EditSteamAchievementWindow>().Init(item.ID, source, target);
    }

    #endregion


    #region 方法

#if UNITY_6000_2_OR_NEWER
    public SteamAchievementListTree() : base(new TreeViewState<int>(), new MultiColumnHeader(CreateDefaultMultiColumnHeaderState()))
#else
    public SteamAchievementListTree() : base(new TreeViewState(), new MultiColumnHeader(CreateDefaultMultiColumnHeaderState()))
#endif

    {
        showBorder = true;
        showAlternatingRowBackgrounds = true;
        rowHeight = 20;

        target = new SteamAchievementData(); 
        
    }

    private void CellGUI(Rect cellRect, SteamAchievementTreeItem item, int column, ref RowGUIArgs args)
    {
        switch (column)
        {
            case 0: // ID
                EditorGUI.LabelField(cellRect, item.ID);
                break;
            case 1: // 源语言 
                EditorGUI.LabelField(cellRect, source != null ? source.language : "Unknown");
                break;

            case 2: // 源名称

                if (source != null && source.models.ContainsKey(item.ID))
                {
                    EditorGUI.LabelField(cellRect, source.models[item.ID].Name);
                }
                else
                {
                    EditorGUI.LabelField(cellRect, "空");
                }

                break;

            case 3: // 源描述
                if (source != null && source.models.ContainsKey(item.ID))
                {
                    EditorGUI.LabelField(cellRect, source.models[item.ID].Des);
                }
                else
                {
                    EditorGUI.LabelField(cellRect, "空");
                }
                break;

            case 4: // 翻译名称

                if (target != null && target.models.ContainsKey(item.ID))
                {
                    EditorGUI.LabelField(cellRect, target.models[item.ID].Name);
                }
                else
                {
                    EditorGUI.LabelField(cellRect, "空");
                }

                break;

            case 5: // 翻译描述

                if (target != null && target.models.ContainsKey(item.ID))
                {
                    EditorGUI.LabelField(cellRect, target.models[item.ID].Des);
                }
                else
                {
                    EditorGUI.LabelField(cellRect, "空");
                }

                break;

            case 6: // 状态

                if (item.request_name_state == TranslateState.InTranslation || item.request_des_state == TranslateState.InTranslation)
                {
                    EditorGUI.SelectableLabel(cellRect, "翻译中...");
                }
                else if (item.request_name_state == TranslateState.Completed && item.request_des_state == TranslateState.Completed)
                {
                    if (string.IsNullOrEmpty(item.error))
                        EditorGUI.SelectableLabel(cellRect, "翻译成功!");
                    else
                        EditorGUI.SelectableLabel(cellRect, item.error);
                }
                else
                {
                    EditorGUI.SelectableLabel(cellRect, string.IsNullOrEmpty(item.error) ? "待翻译..." : item.error);
                }

                break;

        }
    }

#if UNITY_6000_2_OR_NEWER
    private TreeViewItem<int> CreateView()
#else
    private TreeViewItem CreateView()
#endif

    {

#if UNITY_6000_2_OR_NEWER
        TreeViewItem<int> root = new TreeViewItem<int>(0, -1);
#else
        TreeViewItem root = new TreeViewItem(0, -1);
#endif


        int id = 0;

        if (source != null)
        {
            foreach (var item in source.models.Values)
            {
                id++;
                root.AddChild(new SteamAchievementTreeItem(item.ID));
            }
        }

        return root;
    }

#endregion


    public void Init(string file_path)
    {
        // 解析内容 
        source = Parse(file_path);
        isError = source == null;

        Reload();
    }


    private SteamAchievementData Parse(string file_path)
    {

        if (!File.Exists(file_path))
            return null;

        string[] lines = File.ReadAllLines(file_path);

        if (lines.Length < 7) return null;

        if (!lines[0].StartsWith("\"lang\""))
        {
            return null;
        }

        if (!lines[1].StartsWith("{"))
        {
            return null;
        }

        string language = lines[2].TrimStart();

        if (!language.StartsWith("\"Language\""))
            return null;

        string tokens = lines[3].TrimStart();

        if (!tokens.StartsWith("\"Tokens\""))
            return null;

        language = GetValue(lines[2]);

        SteamAchievementData data = new SteamAchievementData();
        data.language = language;

        for (int i = 5; i < lines.Length; i++)
        {
            string key = GetKey(lines[i]);
            string value = GetValue(lines[i]);

            if (string.IsNullOrEmpty(key)) continue;

            if (key.EndsWith("_NAME"))
            {
                // 名称 
                key = key.Substring(0, key.Length - 5);

                if (!data.models.ContainsKey(key))
                    data.models.Add(key, new SteamAchievementModel(key,i));

                data.models[key].Name = value;
            }

            if (key.EndsWith("_DESC"))
            {
                // 描述
                key = key.Substring(0, key.Length - 5);

                if (!data.models.ContainsKey(key))
                    data.models.Add(key, new SteamAchievementModel(key,i));

                data.models[key].Des = value;
            }

        }

        data.file_path = file_path;

        return data;
    }
     
    public void Save(string file_path)
    {

        Debug.LogFormat("保存路径:{0}",file_path);

        if (File.Exists(file_path))
            File.Delete(file_path);

        StringBuilder content = new StringBuilder();

        content.Append("\"lang\"").Append((char)10);

        content.Append("{").Append((char)10);
         
        content.Append("\t").Append("\"Language\"").Append("\t").AppendFormat("\"{0}\"", target.language).Append((char)10);

        content.Append("\t").Append("\"Tokens\"").Append((char)10);

        content.Append("\t").Append("{").Append((char)10);

        List<SteamAchievementModel> models = new List<SteamAchievementModel>();
         
        foreach (var item in target.models.Values)
        {
            models.Add(item);
        }

        models.Sort((a,b) => { return a.order.CompareTo(b.order); });

        for (int i = 0; i < models.Count; i++)
        { 
            SteamAchievementModel model = models[i];

            content.Append("\t\t").AppendFormat("\"{0}_NAME\"", model.ID).Append("\t").AppendFormat("\"{0}\"", model.Name).Append((char)10);
            content.Append("\t\t").AppendFormat("\"{0}_DESC\"", model.ID).Append("\t").AppendFormat("\"{0}\"", model.Des).Append((char)10);
        }
         
        content.Append("\t").Append("}").Append((char)10);

        content.Append("}");
         

        byte[] bytes = Encoding.UTF8.GetBytes(content.ToString());

        File.WriteAllText(file_path, Encoding.UTF8.GetString(bytes),Encoding.UTF8);
    }

    private string GetKey(string line)
    {
        StringBuilder key = new StringBuilder();

        int count = 0;

        for (int i = 0; i < line.Length; i++)
        {
            if (line[i] == '\"')
            {
                count++;
                continue;
            }

            if (count == 1)
            {
                key.Append(line[i]);
            }

            if (count == 2)
            {
                break;
            }
        }

        return key.ToString();

    }

    private string GetValue(string line)
    {

        StringBuilder value = new StringBuilder();

        int count = 0;

        for (int i = 0; i < line.Length; i++)
        {
            if (line[i] == '\"')
            {
                count++;
                continue;
            }

            if (count == 3)
            {
                value.Append(line[i]);
            }

            if (count == 4)
            {
                break;
            }
        }

        return value.ToString();

    }


    public override void OnGUI(Rect rect)
    {
        base.OnGUI(rect);


        if (source != null && rootItem != null)
        {
            foreach (var item in source.models.Values)
            {
                SteamAchievementTreeItem s = FindItem(item.ID.GetHashCode(), rootItem) as SteamAchievementTreeItem;
                if (s == null) continue;
                s.Update();
            }
        } 
    }

#if UNITY_6000_2_OR_NEWER
    public List<TreeViewItem<int>> GetAllItems()
#else
    public List<TreeViewItem> GetAllItems()
#endif

    {
        allItems.Clear();
        if (rootItem == null) return allItems;

        if (source != null)
        {
            foreach (var item in source.models.Values)
            {  
                SteamAchievementTreeItem s = FindItem(item.ID.GetHashCode(), rootItem) as SteamAchievementTreeItem;
                if (s == null) continue;
                allItems.Add(s);
            } 
        }

        return allItems;
    }
}



public class SteamAchievementTranslateWindow : EditorWindow
{ 
    [MenuItem("Window/XFKT/XFGameFramework/InstalledExtension/Localization/Steam成就翻译", false, 100)]
    static void Open()
    {
        GetWindow<SteamAchievementTranslateWindow>();
    }

    private string file_path;

    private SteamAchievementListTree steamAchievementListTree;

    private GUIStyle errorStyle;

    private TranslateAPI api;

    private SystemLanguage to;

    private bool need_intervene = true;

    private string vocabId;

    // 是否正在翻译中...
    private bool translate = false;

    private GUIContent toContent;

    private GUIStyle dropdownStyle;

    private float lastRepaintCount;

    private void Awake()
    {
        titleContent.text = "Steam成就翻译";
    }

    private void OnGUI()
    {
        OnGUI_Path();

        if (steamAchievementListTree == null)
        {
            steamAchievementListTree = new SteamAchievementListTree();
            steamAchievementListTree.Init(file_path);
        }

        if (steamAchievementListTree.isError && !string.IsNullOrEmpty(file_path))
        {
            if (errorStyle == null)
            {
                errorStyle = new GUIStyle(GUI.skin.label);
                errorStyle.normal.textColor = Color.red;
            }

            EditorGUILayout.LabelField("文件解析失败!", errorStyle);
        }

        Rect rect = GUILayoutUtility.GetRect(0, 300);
        rect.height = position.height - rect.y - 50;

        steamAchievementListTree.OnGUI(rect);

        GUILayout.FlexibleSpace();

        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();

        EditorGUI.BeginDisabledGroup(steamAchievementListTree == null || steamAchievementListTree.source == null);

        // 
        OnGUI_Api();

        OnGUI_To();

        OnGUI_Intervene();

        GUILayout.BeginVertical();

        EditorGUI.BeginDisabledGroup(translate);

        EditorGUI.BeginDisabledGroup(steamAchievementListTree != null && steamAchievementListTree.target.Empty);

        if (GUILayout.Button("保存", GUILayout.Width(80)))
        {
            Save();
        }
        EditorGUI.EndDisabledGroup();



        if (GUILayout.Button("翻译",GUILayout.Width(80)))
        {
            StartTranslate();
        }

        EditorGUI.EndDisabledGroup();

        EditorGUI.EndDisabledGroup();

        GUILayout.EndVertical();

        GUILayout.EndHorizontal();

        GUILayout.Space(5);

    }

    private void OnGUI_Path()
    {
        GUILayout.Space(3);

        EditorGUI.BeginChangeCheck();
        EditorGUILayout.LabelField(string.Empty, "成就文件路径", "BoldLabel");

        EditorGUILayout.SelectableLabel(string.IsNullOrEmpty(file_path) ? "空" : file_path);

        //Debug.Log(file_path);

        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();

        if (GUILayout.Button("选取文件", GUILayout.Width(80)))
        {
            string path = EditorUtility.OpenFilePanel("请选择Steam成就文件", string.Empty, "*");

            if (!string.IsNullOrEmpty(path))
            {

                file_path = path;

                if (steamAchievementListTree != null)
                    steamAchievementListTree.Init(file_path);


                if (steamAchievementListTree != null && steamAchievementListTree.source != null) 
                {

                    foreach (var item in SteamTranslateController.steam_language.Keys)
                    {
                        if(string.IsNullOrEmpty(SteamTranslateController.steam_language[item]))
                            continue;

                        if (SteamTranslateController.steam_language[item] == steamAchievementListTree.source.language)
                            continue;

                        to = item;

                        steamAchievementListTree.target.language = SteamTranslateController.GetSteamLanguage(to); 
                        break;
                    }
                }

            }

        }
        GUILayout.EndHorizontal();


        if(string.IsNullOrEmpty(file_path))
            steamAchievementListTree = null;
    }
     
    private void Update()
    {
        lastRepaintCount++;
        if (lastRepaintCount > 15) 
        { 
            Repaint();
            lastRepaintCount = 0;
        }

        // 翻译
        Translate();
    }

    private void Translate()
    {

        if (!translate) return;

        if (steamAchievementListTree == null) return;


        if (AllCompleted())
        { 
            translate = false;
            ShowNotification(new GUIContent("已全部翻译!"));
            return; 
        }
#if UNITY_6000_2_OR_NEWER
        List<TreeViewItem<int>> items = steamAchievementListTree.GetAllItems();
#else
        List<TreeViewItem> items = steamAchievementListTree.GetAllItems();
#endif


        if (items == null || items.Count == 0)
            return;
          
        foreach (var item in items)
        {
            SteamAchievementTreeItem i = item as SteamAchievementTreeItem;
            if (i == null) continue;

            //if (i.request_name_state != TranslateState.Wait || i.request_des_state != TranslateState.Wait)
            //    continue;
             
            if (GetTranslateCount(items) < 20)
            {
                i.Translate(api, steamAchievementListTree.source, steamAchievementListTree.target, to, need_intervene ? 1 : 0, vocabId);
            } 
        }
    }


    private bool AllCompleted()
    {

        if (steamAchievementListTree == null) return true;

        bool completed = true;
#if UNITY_6000_2_OR_NEWER
        List<TreeViewItem<int>> items = steamAchievementListTree.GetAllItems();
#else
        List<TreeViewItem> items = steamAchievementListTree.GetAllItems();
#endif


        if (items != null && items.Count > 0)
        {

            foreach (var item in items)
            {
                SteamAchievementTreeItem i = item as SteamAchievementTreeItem;
                if (i == null) continue;

                if (i.request_name_state == TranslateState.Wait || i.request_des_state == TranslateState.Wait)
                    return false;
            }
        }

        return completed;
    }

    /// <summary>
    /// 正在翻译中的数量
    /// </summary>
    /// <returns></returns>
#if UNITY_6000_2_OR_NEWER
    private int GetTranslateCount(List<TreeViewItem<int>> items)
#else
    private int GetTranslateCount(List<TreeViewItem> items)
#endif

    {
        int count = 0;
         
        if (items  != null)
        {

            foreach (var item in items)
            {
                SteamAchievementTreeItem i = item as SteamAchievementTreeItem;
                if (i == null) continue;

                if (i.request_name_state == TranslateState.InTranslation || i.request_des_state == TranslateState.InTranslation)
                    count++;
            }
        }

        return count;
    }
     
    private void OnGUI_Api()
    {
        GUILayout.BeginVertical();

        EditorGUILayout.LabelField("翻译方式"); 
        api = (TranslateAPI)EditorGUILayout.EnumPopup(api);
        
        GUILayout.EndVertical();
    }

    private void OnGUI_To()
    { 

        if (toContent == null)
            toContent = new GUIContent();

        toContent.text = to.ToString();
         
        if (dropdownStyle == null)
            dropdownStyle = new GUIStyle("DropDown");


        GUILayout.BeginVertical();
        EditorGUILayout.LabelField("目标语言");
        Rect r = GUILayoutUtility.GetRect(toContent, dropdownStyle, GUILayout.ExpandWidth(true));
        if (EditorGUI.DropdownButton(r, toContent, FocusType.Passive, dropdownStyle)) 
        {

            GenericMenu menu = new GenericMenu();

            string[] names = Enum.GetNames(typeof(SystemLanguage));

            foreach (var item in names)
            {
                SystemLanguage language = (SystemLanguage)Enum.Parse(typeof(SystemLanguage), item);
                
                string steam_language = SteamTranslateController.GetSteamLanguage(language);

                if (string.IsNullOrEmpty(steam_language)) continue;

                SystemLanguage from = SteamTranslateController.GetSystemLanguage(steamAchievementListTree.source.language);

                if (language == from)
                {
                    menu.AddDisabledItem(new GUIContent(language.ToString()));
                }
                else 
                {
                    menu.AddItem(new GUIContent(language.ToString()), language == to, () => 
                    {
                        to = language;

                        // 清理

                        if (steamAchievementListTree.target != null) 
                        {                             
                            steamAchievementListTree.target.language = SteamTranslateController.GetSteamLanguage(to);
                            steamAchievementListTree.target.models.Clear();
                        }


                        steamAchievementListTree.Reload();
                    });
                }

            }


            menu.DropDown(r);

        }
        GUILayout.EndVertical();

        if (steamAchievementListTree != null)
            steamAchievementListTree.target.language = SteamTranslateController.GetSteamLanguage(to);

    }

    private void OnGUI_Intervene()
    {
        GUILayout.Space(5);

        switch (api)
        {
            case TranslateAPI.Baidu:
                GUILayout.BeginVertical();
                EditorGUILayout.LabelField("启用术语表");
                need_intervene = EditorGUILayout.Toggle(need_intervene);
                GUILayout.EndVertical();
                break;
            case TranslateAPI.Youdao:
                GUILayout.BeginVertical();
                EditorGUILayout.LabelField( "术语表id");
                vocabId = EditorGUILayout.TextField(vocabId);
                GUILayout.EndVertical();
                break;
        }

    }


    private void StartTranslate() 
    {

        switch (api)
        {
            case TranslateAPI.Baidu:

                if (string.IsNullOrEmpty(LocalizationSettings.Instance.baidu.app_id) || string.IsNullOrEmpty(LocalizationSettings.Instance.baidu.secret_key))
                {
                    if (EditorUtility.DisplayDialog("提示", "app_id 或 密钥为空,请设置后再试!", "打开设置"))
                        LocalizationSettings.Instance.OpenProjectSettings("XFGameFramework/Localization");
                    return;
                }

                break;
            case TranslateAPI.Youdao:

                if (string.IsNullOrEmpty(LocalizationSettings.Instance.youdao.app_id) || string.IsNullOrEmpty(LocalizationSettings.Instance.youdao.secret_key))
                {
                    if (EditorUtility.DisplayDialog("提示", "app_id 或 密钥为空,请设置后再试!", "打开设置"))
                        LocalizationSettings.Instance.OpenProjectSettings("XFGameFramework/Localization");
                    return;
                }


                break; 
        }
         

        translate = true;

        if (steamAchievementListTree == null) return;
#if UNITY_6000_2_OR_NEWER
        List<TreeViewItem<int>> items = steamAchievementListTree.GetAllItems();
#else
        List<TreeViewItem> items = steamAchievementListTree.GetAllItems();
#endif

        if (items != null && items.Count > 0)
        {

            foreach (var item in items)
            {
                SteamAchievementTreeItem i = item as SteamAchievementTreeItem;
                if (i == null) continue;

                if (!string.IsNullOrEmpty(i.error))
                {
                    if (!i.des_translate_success)
                        i.request_des_state = TranslateState.Wait;
                    if(!i.name_translate_success)
                        i.request_name_state = TranslateState.Wait;

                    i.retry_count = 0;
                }
                
            }
        }

    }


    private void Save() 
    {
        string dir = Path.GetDirectoryName(file_path);
        
        string file_name = Path.GetFileName(file_path);

        dir = EditorUtility.OpenFolderPanel("请选择目标文件夹", dir,string.Empty);

        if (string.IsNullOrEmpty(dir)) return;

        if (string.IsNullOrEmpty(file_name))
        {
            file_name = steamAchievementListTree.target.language;
        }
        else 
        {
            file_name = file_name.Replace(steamAchievementListTree.source.language, steamAchievementListTree.target.language);
        }


        steamAchievementListTree.Save(string.Format("{0}/{1}", dir, file_name));
    }

}
